var pokemons = new Array; // tableau qui contient tous les pokemons et leurs positions
var skys;
var imgPokeballCursor;
var imgPokeballTop;
var imgPokeballBottom;
var imgWin;
var nbPokemon;
var speedSky;
var capturing; // etat pour savoir si on est en train de capturer un pokemon
var canvas; // Gestion de la balise canvas
var context; // Gestion du contexte 2d du canvas
var mouse; // Déclaration de la variable qui gère la position du curseu
var timerCapture;
var temp_x = null; //fonction animateCapture
var temp_y = null; //fonction animateCapture
var offset = 0; //fonction animateCapture

//création d'un pokemon
function Pokemon(name,posX,posY,death,visible,posXSprite,posYSprite,width,height,speedX,speedY) {
	this.name=name;
	this.posX=posX;
	this.posY=posY;
	this.death=death;
	this.visible = visible;
	this.posXSprite = posXSprite;
	this.posYSprite = posYSprite;
	this.width = width;
	this.height = height;
	this.speedX = speedX;
	this.speedY = speedY;
}

function imgSky(posX,posY,posXSprite,posYSprite,width,height){
	this.posX=posX;
	this.posY=posY;
	this.posXSprite = posXSprite;
	this.posYSprite = posYSprite;
	this.width = width;
	this.height = height;
}

// Initialisation du jeu
function initGame()
{
	canvas = document.getElementById("headerGame");
	context = canvas.getContext('2d');
		
	canvas.addEventListener("mousedown", function() // Evénement lors du clic
	{
		if(nbPokemon > 0)
			killPokemon(mouse.pos.x,mouse.pos.y); // Essaye de tuer un pokemon
		else {
			// click lorsque le jeu est gagné
			if(mouse.pos.x > ((canvas.width/2)-(imgWin.width/2)) 
					&& mouse.pos.x < ((canvas.width/2)+(imgWin.width/2)) 
					&& mouse.pos.y > 50 && mouse.pos.y < 250)
				document.location.href = Routing.generate("fos_user_profile_show");
				//initValues();
		}
	}, false);
     
	// Evénement qui met à jour la position du curseur
    canvas.addEventListener("mousemove", function(evt)
	{
        var pos = getMousePos(canvas, evt);
        mouse.pos.x = pos.x;
        mouse.pos.y = pos.y;
    });
    
    initValues();
}


function initValues()
{
	speedSky = 0.1;
	canvas.style.cursor = 'none';
    
    mouse = {
        pos: {}
    };   
    capturing = {
    	state : false,
    	step : 0
    };   
    imgPokeballCursor = {
    	posXSprite : 0,
    	posYSprite : 1389,
    	width : 50,
    	height : 80
    };   
    imgPokeballTop = {
        	posXSprite : 50,
        	posYSprite : 1389,
        	width : 50,
        	height : 35
    };
    imgPokeballBottom = {
        	posXSprite : 50,
        	posYSprite : 1429,
        	width : 50,
        	height : 25
    };
    imgWin = {
        	posXSprite : 0,
        	posYSprite : 466,
        	width : 700,
        	height : 250
    };
    	
	/* initialisation des positions */
    // name,posX,posY,death,visible,posXSprite,posYSprite,width,height,speedX,speedY
    // aeromite
    pokemons.push(new Pokemon("aeromite",canvas.width+20,160,false,false,0,0,130,87,-1,-0.1));
    //artikodin
    pokemons.push(new Pokemon("artikodin",-140,200,false,false,0,92,140,153,0.8,-0.1));
    // elektor
    pokemons.push(new Pokemon("elektor",730,180,false,false,0,250,160,109,-1,-0.4));
    // fantominus
    pokemons.push(new Pokemon("fantominus",canvas.width-10,200,false,false,0,364,100,97,-1.6,-0.2));
    // lugia
    pokemons.push(new Pokemon("lugia",canvas.width+50,120,false,false,0,721,140,108,-1.3,-0.2));
    // mew
    pokemons.push(new Pokemon("mew",canvas.width-100,350,false,false,0,834,140,119,-0.4,-0.2));
    // papilusion
    pokemons.push(new Pokemon("papilusion",-20,75,false,false,0,958,130,120,0.6,-0.3));
    // roucarnage
    pokemons.push(new Pokemon("roucarnage",-40,110,false,false,0,1170,120,128,0.3,-0.7));
    
    // sky
    initSky();
    
    nbPokemon = pokemons.length;
    
    // lancement des timout d'apparition
    setInitDelay();
	animate(); // Lancement de l'animation
}

function setInitDelay(){
	setInitDelayAeromite();
	setInitDelayArtikodin();
	setInitDelayElektor();
	setInitDelayFantominus();
	setInitDelayLugia();
	setInitDelayMew();
	setInitDelayPapilusion();
	setInitDelayRoucarnage();
}

function setPokemonInvisible(ind){
	pokemons[ind].visible = false;
}

function setInitDelayAeromite(){
	window.setTimeout("initAeromite()", 2000);
}
function setInitDelayArtikodin(){
	window.setTimeout("initArtikodin()", 3000);
}
function setInitDelayElektor(){
	window.setTimeout("initElektor()", 3800);
}
function setInitDelayFantominus(){
	window.setTimeout("initFantominus()", 2800);
}
function setInitDelayLugia(){
	window.setTimeout("initLugia()", 5800);
}
function setInitDelayMew(){
	window.setTimeout("initMew()", 10000);
}
function setInitDelayPapilusion(){
	window.setTimeout("initPapilusion()", 1000);
}
function setInitDelayRoucarnage(){
	window.setTimeout("initRoucarnage()", 7000);
}

function initAeromite(){
	for(var i=0;i<nbPokemon;i++){
		if(pokemons[i].name == "aeromite"){
			pokemons[i].posX = canvas.width+20;
			pokemons[i].posY = 160;
			pokemons[i].visible = true;
		}
	}
}
function initArtikodin(){
	for(var i=0;i<nbPokemon;i++){
		if(pokemons[i].name == "artikodin"){
			pokemons[i].posX = -140;
			pokemons[i].posY = 200;
			pokemons[i].visible = true;
		}
	}
}
function initElektor(){
	for(var i=0;i<nbPokemon;i++){
		if(pokemons[i].name == "elektor"){
			pokemons[i].posX = 730;
			pokemons[i].posY = 180;
			pokemons[i].visible = true;
		}
	}
}
function initFantominus(){
	for(var i=0;i<nbPokemon;i++){
		if(pokemons[i].name == "fantominus"){
			pokemons[i].posX = canvas.width-10;
			pokemons[i].posY = 200;
			pokemons[i].visible = true;
		}
	}
}
function initLugia(){
	for(var i=0;i<nbPokemon;i++){
		if(pokemons[i].name == "lugia"){
			pokemons[i].posX = canvas.width+50;
			pokemons[i].posY = 120;
			pokemons[i].visible = true;
		}
	}
}
function initMew(){
	for(var i=0;i<nbPokemon;i++){
		if(pokemons[i].name == "mew"){
			pokemons[i].posX = canvas.width-100;
			pokemons[i].posY = 350;
			pokemons[i].visible = true;
		}
	}
}
function initPapilusion(){
	for(var i=0;i<nbPokemon;i++){
		if(pokemons[i].name == "papilusion"){
			pokemons[i].posX = -20;
			pokemons[i].posY = 75;
			pokemons[i].visible = true;
		}
	}
}
function initRoucarnage(){
	for(var i=0;i<nbPokemon;i++){
		if(pokemons[i].name == "roucarnage"){
			pokemons[i].posX = -40;
			pokemons[i].posY = 110;
			pokemons[i].visible = true;
		}
	}
}

function initSky(){
	skys = new Array;
    skys.push(new imgSky(100,10,0,1303,128,44));
    skys.push(new imgSky(canvas.width-300,10,0,1303,128,44));
    skys.push(new imgSky(canvas.width/2,10,0,1352,71,32));
}


//Fonction pour vérifier si on clique bien sur un pokemon
function killPokemon(mouseX,mouseY)
{
	for(var i=0;i < nbPokemon; i++)
	{
		if((mouseX < (pokemons[i].posX + (pokemons[i].width * 0.80))) && 
			(mouseX > (pokemons[i].posX + (pokemons[i].width * 0.20))) && 
			(mouseY < (pokemons[i].posY + (pokemons[i].height * 0.75))) &&
			(mouseY > (pokemons[i].posY + (pokemons[i].height * 0.25))) &&
			pokemons[i].visible == true)
		{
			pokemons[i].death = true;
			capturing.state = true;
		}
	}
}

//Fonction qui anime les pokemons et rafraichit la page en boucle         
function animate()
{
	context.clearRect(0, 0, canvas.width, canvas.height);
	drawSky();
	drawLogoPokeshop();
	
	if(!capturing.state){		
		// Animation des pokemons
		for(var i=0;i<nbPokemon;i++)
		{
			pokemons[i].posX += pokemons[i].speedX;
			pokemons[i].posY += pokemons[i].speedY;
			animateImage(pokemons[i].posX,pokemons[i].posY,i);
		}
		
		drawCrossHair();
		
		// Rafraichissement du Frame avec appel récursif de la fonction
	    requestAnimFrame(function()
		{
			animate();
	    });
	}
	// capture d'un pokemon
	else {
		if(capturing.step == 0){
			timerCapture = setInterval(animateCapture, 20);
		}
		// Animation des pokemons
		for(var i=0;i<nbPokemon;i++)
		{
			animateImage(pokemons[i].posX,pokemons[i].posY,i);
		}
	}
}


//Rafraichissement du Frame
window.requestAnimFrame = (function(callback)
{
    return window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback)
	{
        window.setTimeout(callback, 1000 / 60);
    };
})();

var outCanvas;
function animateImage(posX,posY,numPokemon)
{
	outCanvas = false;
	if(pokemons[numPokemon].visible == true)
	{
		if(!(pokemons[numPokemon].death) && !(capturing.state))
		{
			// si le pokemon sort du cadre on le replace
			if(posX < (-150))
			{
				outCanvas = true;
			}
			else if(posX > canvas.width+150)
			{
				outCanvas = true;
			}
			
			if(posY < (-150))
			{
				outCanvas = true;
			}
			
			if(outCanvas)
			{
				setPokemonInvisible(numPokemon);
				switch(pokemons[numPokemon].name){
				case "aeromite" : setInitDelayAeromite();break;
				case "artikodin" : setInitDelayArtikodin();break;
				case "elektor" : setInitDelayElektor();break;
				case "fantominus" : setInitDelayFantominus();break;
				case "lugia" : setInitDelayLugia();break;
				case "mew" : setInitDelayMew();break;
				case "papilusion" : setInitDelayPapilusion();break;
				case "roucarnage" : setInitDelayRoucarnage();break;
				}
			}
		}
		
		context.drawImage(imgSpriteGame,
				pokemons[numPokemon].posXSprite,
				pokemons[numPokemon].posYSprite,
				pokemons[numPokemon].width,
				pokemons[numPokemon].height,
				pokemons[numPokemon].posX,
				pokemons[numPokemon].posY,
				pokemons[numPokemon].width,
				pokemons[numPokemon].height
		);
	}
}


//Fonction de dessin du viseur
function drawCrossHair(){         
    if (mouse.pos.x && mouse.pos.y) {
    	context.drawImage(imgSpriteGame,
    			imgPokeballCursor.posXSprite,
    			imgPokeballCursor.posYSprite,
    			imgPokeballCursor.width,
    			imgPokeballCursor.height,
    			mouse.pos.x-25,
    			mouse.pos.y-25,
				imgPokeballCursor.width,
				imgPokeballCursor.height
		);
    }
}


//Fonction qui retourne la position de la souris
function getMousePos(canvas, evt)
{
    // get canvas position
    var obj = canvas;
    var top = 0;
    var left = 0;
    while (obj.tagName != 'BODY') {
        top += obj.offsetTop;
        left += obj.offsetLeft;
        obj = obj.offsetParent;
    }
                
    // return relative mouse position
    var mouseX = evt.clientX - left + window.pageXOffset;
    var mouseY = evt.clientY - top + window.pageYOffset;
    return {
        x: mouseX,
        y: mouseY
    };
}


function animateCapture(){
	context = canvas.getContext('2d');
	context.clearRect(0, 0, canvas.width, canvas.height);
	drawSky();
	drawLogoPokeshop();
	for(var i=0;i<nbPokemon;i++)
	{
		animateImage(pokemons[i].posX,pokemons[i].posY,i);
	}
	
	var mouse_x,mouse_y;
	if(capturing.step==0){
		temp_x = mouse.pos.x;
		temp_y = mouse.pos.y;
		mouse_x = temp_x;
		mouse_y = temp_y;
	}
	else {
		mouse_x = temp_x;
		mouse_y = temp_y;
	}
	capturing.step++;
	
	//context.globalCompositeOperation = 'source-over';
	if(capturing.step == 1){
		offset++;
		context.drawImage(imgSpriteGame,
    			imgPokeballCursor.posXSprite,
    			imgPokeballCursor.posYSprite,
    			imgPokeballCursor.width,
    			imgPokeballCursor.height,
    			mouse.pos.x-25,
    			mouse.pos.y-25,
				imgPokeballCursor.width,
				imgPokeballCursor.height
		);
	}
	else 
	{
		if(capturing.step <= 20)
		{
			offset++;
			// pokeball bottom
			context.drawImage(
					imgSpriteGame,
					imgPokeballBottom.posXSprite,imgPokeballBottom.posYSprite,
					imgPokeballBottom.width,imgPokeballBottom.height,
					mouse_x-25,mouse_y+offset,
					imgPokeballBottom.width,imgPokeballBottom.height
			);
			// pokeball top
			context.drawImage(
				imgSpriteGame,
				imgPokeballTop.posXSprite,imgPokeballTop.posYSprite,
				imgPokeballTop.width,imgPokeballTop.height,
				mouse_x-25,mouse_y-25-offset,
				imgPokeballTop.width,imgPokeballTop.height
			);
		}
		else {
			if(capturing.step > 40){
				capturing.step = 0;
				capturing.state = false;
				offset = 0;
				triPokemon();
				nbPokemon--;
				clearInterval(timerCapture);
				if(nbPokemon == 0){
					context.clearRect(0, 0, canvas.width, canvas.height);
					//canvas.style.cursor = 'pointer';
					/*context.drawImage(
							imgSpriteGame,
							imgWin.posXSprite,imgWin.posYSprite,
							imgWin.width,imgWin.height,
							(canvas.width/2)-(imgWin.width/2),25,
							imgWin.width,imgWin.height
					);*/
					addCodeReductionFromCanvas();
				}
				else{
					animate();
				}
			}
			else {
				offset--;
				// pokeball bottom
				context.drawImage(
						imgSpriteGame,
						imgPokeballBottom.posXSprite,imgPokeballBottom.posYSprite,
						imgPokeballBottom.width,imgPokeballBottom.height,
						mouse_x-25,mouse_y+offset,
						imgPokeballBottom.width,imgPokeballBottom.height
				);
				// pokeball top
				context.drawImage(
						imgSpriteGame,
						imgPokeballTop.posXSprite,imgPokeballTop.posYSprite,
						imgPokeballTop.width,imgPokeballTop.height,
						mouse_x-25,mouse_y-25-offset,
						imgPokeballTop.width,imgPokeballTop.height
				);
			}
		}
	}
}

function displayCanvas()
{
	// le canvas prend la taille de son parent
	// qui lui prend la taille de l'ecran
	canvas = document.getElementById("headerGame");
	window.addEventListener('resize',resizeCanvas,false);
	function resizeCanvas(){
		canvas.width = document.getElementById("canvas").offsetWidth;
		if(nbPokemon == 0){
			context.clearRect(0, 0, canvas.width, canvas.height);
			canvas.style.cursor = 'pointer';
			context.drawImage(
					imgSpriteGame,
					imgWin.posXSprite,imgWin.posYSprite,
					imgWin.width,imgWin.height,
					(canvas.width/2)-(imgWin.width/2),25,
					imgWin.width,imgWin.height
			);
		}
	}
	resizeCanvas();
}

function triPokemon(){
	var id = null;
	for(var i=0; i < nbPokemon;i++){
		if(pokemons[i].death){
			id = i;
		}
	}
	pokemons.splice(id,1);
}

function drawLogoPokeshop(){
	context.drawImage(logoPokeshop,
			(canvas.width/2)-(logoPokeshop.width/2),
			20);	
}

function drawSky(){
	var i;
	for(i = 0; i < skys.length; i++){
		skys[i].posX += speedSky;
		if(skys[i].posX > canvas.width){
			skys[i].posX = skys[i].width * (-1);
		}
		context.drawImage(imgSpriteGame,
				skys[i].posXSprite,
				skys[i].posYSprite,
				skys[i].width,
				skys[i].height,
				skys[i].posX,
				skys[i].posY,
				skys[i].width,
				skys[i].height
		);
	}
}

function addCodeReductionFromCanvas(){
	initPopup();
	$.ajax({
        type: "POST",
        url: Routing.generate("add_code_reduction_from_canvas"),
        success: function(data){
        	$("#imgLoader").hide();
        	$("#resultAjax").html(data);
        	$('#_mypopup').click(closePopup);
           canvas.style.cursor = 'pointer';
           context.drawImage(
					imgSpriteGame,
					imgWin.posXSprite,imgWin.posYSprite,
					imgWin.width,imgWin.height,
					(canvas.width/2)-(imgWin.width/2),25,
					imgWin.width,imgWin.height
			);
        },
        error: function(){
        	$("#imgLoader").hide();
        	$("#resultAjax").html("Une erreur s'est produite, veuillez retenter votre chance");
        	$('#_mypopup').click(closePopup);
		}
    });
}

function closePopup() {
    $("#_mypopup").html("");
    $("#_mypopup").hide();
}
function initPopup() {
    $('body').append('<div id="_mypopup">'+
    	'<div id="popupGame">'+
    	'<img id="imgLoader" src="'+imgLoader.src+'"/><br>'+
    	'<span id="resultAjax"></span></div></div>');
    $('#_mypopup').css( { 'text-align': "center", position: "fixed", 
                        left:0, top:0, width: "100%", height: "100%", 
                        "background-color": "rgba(0, 0, 0, 0.7)", 'z-index':2000, 'padding-top':'200px'} );
    $('#_mypopup').show();
}